package ua.org.groovy.gs.ui;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferStrategy;

import ua.org.groovy.gs.core.World;

public class GroovyCanvas extends Canvas implements Runnable {
	private BufferStrategy strategy = null;
	
	private World gameWorld;
	
	private boolean gameRunning = true;
	
	
	public GroovyCanvas(World world) {
		setIgnoreRepaint(true);
		this.gameWorld = world;
	}
	
	public void run() {
		long lastLoopTime = System.nanoTime();
		while (gameRunning) {
			if (strategy == null) {
				createBufferStrategy(2);
				strategy = getBufferStrategy();
				lastLoopTime = System.nanoTime();
			}
			
			int delta = (int) ((System.nanoTime() - lastLoopTime)/1000000);
			lastLoopTime = System.nanoTime();

			Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
			g.setRenderingHint(
					RenderingHints.KEY_ANTIALIASING, 
					RenderingHints.VALUE_ANTIALIAS_ON);
			g.setColor(Color.black);
			g.fillRect(0, 0, getWidth(), getHeight());
			
			gameWorld.update(delta);
			gameWorld.draw(g);
			
			g.dispose();
			strategy.show();
	
			try { Thread.sleep(5, 0);} catch (Exception e) {}
		}
	}
}